<script setup>
import { nextTick, onMounted, onUnmounted, ref, shallowRef, watch } from 'vue'
import { nanoid } from 'nanoid'
import * as echarts from 'echarts'
import 'echarts-gl'

defineOptions({
  name: 'DrawEcharts',
})

const emits = defineEmits(['onload'])

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  width: {
    type: String,
    default: '',
  },
  height: {
    type: String,
    default: '',
  },
  lazy: {
    type: Boolean,
    default: false,
  },
  theme: {
    type: String,
    default: 'dark',
  },
  options: {
    type: Object,
    default: () => ({}),
  },
})

const echartsRef = ref()
const chart = shallowRef()

const _width = ref()
const _height = ref()

const _id = ref(props.id || nanoid())

watch(
  () => props.options,
  () => {
    nextTick(() => {
      initEcharts()
    })
  },
  {
    immediate: !props.lazy,
  },
)

const initEcharts = () => {
  if (!chart.value) {
    chart.value = echarts.init(document.getElementById(_id.value), props.theme, {
      width: props.width || _width.value,
      height: props.height || _height.value,
    })
  }
  chart.value.setOption(props.options)
  emits('onload', chart.value)
}

const getParentWH = () => {
  if (echartsRef.value && echartsRef.value.parentElement) {
    // 获取元素父级宽高
    const { offsetWidth, offsetHeight } = echartsRef.value.parentElement
    _width.value = offsetWidth
    _height.value = offsetHeight
    return [offsetWidth, offsetHeight]
  }
  return [0, 0]
}

const resize = () => {
  if (!chart.value) return
  const [width, height] = getParentWH()
  chart.value.resize({
    width: props.width || width,
    height: props.height || height,
  })
}

const updateOption = (options) => {
  if (!chart.value) return
  chart.value.setOption(options)
}

onMounted(() => {
  getParentWH()
  window.addEventListener('resize', resize)
})

onUnmounted(() => {
  if (chart.value) {
    chart.value.dispose()
  }
  window.removeEventListener('resize', resize)
})

defineExpose({
  chart,
  initEcharts,
  updateOption,
  resize,
  getParentWH,
})
</script>

<template>
  <div ref="echartsRef" class="echarts-container" :id="_id"></div>
</template>

<style lang="scss" scoped></style>
